package com.example.testhotload;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;

public class AppInnerDownloader {
    public final static String SD_FOLDER = Environment.getExternalStorageDirectory()+"/VersionChecker/";
    private static final String TAG  = AppInnerDownloader.class.getSimpleName();

    @SuppressWarnings("unused")
    public static void downloadApk(final Context mContext, final String downUrl, final  String apkName){
        final ProgressDialog pd;
        pd = new ProgressDialog(mContext);
        pd.setCancelable(false);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载安装包，请稍后");
        pd.setTitle("版本升级");
        pd.show();
        new Thread(){
            @Override
            public void run(){
                try {
                    File file = downloadFile(downUrl,apkName,pd);
                    sleep(3000);
                    installApk(mContext,file);
                    pd.dismiss();
                }catch (Exception e){
                    e.printStackTrace();
                    pd.dismiss();
                }
            }
        }.start();
    }

    private static File downloadFile(String path, String appName, ProgressDialog pd) throws  Exception{
        if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5000);
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            String fileName = SD_FOLDER+appName+".apk";
            File file = new File(fileName);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len ;
            int total =0;
            while((len=bis.read(buffer))!=-1){
                fos.write(buffer,0,len);
                total+=len;
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        }else{
            throw new IOException("未发现有SD卡");
        }
    }

    public  static void installApk(Context ctx,File file){
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(ctx, "com.example.testhotload.fileprovider", file);
        } else {
            uri= Uri.fromFile(file);
        }
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(uri,"application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        ctx.startActivity(install);
    }

    private static double getLocalVersion(Context context){
        PackageManager mg = context.getPackageManager();
        PackageInfo info = null;
        try {
            info = mg.getPackageInfo(context.getPackageName(),0);

        }catch (PackageManager.NameNotFoundException e){
            Log.e(TAG,"获取应用程序版本失败，原因："+e.getMessage());
            return 0.0;
        }
        return Double.valueOf(info.versionName);
    }

    public static String bytes2kb(long bytes){
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024*1024);
        float returnValue = filesize.divide(megabyte,2,BigDecimal.ROUND_UP).floatValue();
        if(returnValue>1)return returnValue+"MB";
        BigDecimal kilobyte = new BigDecimal(1024);
         returnValue = filesize.divide(kilobyte,2,BigDecimal.ROUND_UP).floatValue();
         return returnValue+"KB";
    }
}
